from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.models import Group as Project
from django.contrib.auth.models import User

from settings import MEDIA_ROOT

from glob import glob

@login_required
def index(request):
   return render_to_response('index.html')

def uploads(request):
   return render_to_response('uploads.html', {'files': glob(MEDIA_ROOT+'/*')})

@login_required
def profile(request):
   return render_to_response('registration/profile.html', {'user': request.user})

@user_passes_test(lambda u:u.is_staff)
def project_manage(request):
   
   if request.method=='GET':
      if 'project' in request.GET:
         return render_to_response(
            'rat/project_manage.html',
            {'project': Project.objects.get(name=request.GET['project']),
             'non_members': User.objects.all()}) # XXX non members only
      return render_to_response(
         'rat/project_manage.html',
         {'project_list': Project.objects.all()})

   POST = request.POST
   if 'project' in POST:
      project = request.POST['project']
      g = Project.objects.get(pk=project)

   if 'new_user' in POST and POST['new_user']:
      v = POST['new_user']
      error = None
      try:
         u = User.objects.create_user(v, '%s@%s.com' % (v, g), v)
      except Exception,msg:
         error = msg
      else:
         u.save()
         u.groups.add(g)
      return render_to_response(
         'rat/project_manage.html',
         {'project': Project.objects.get(pk=project),
          'non_members': User.objects.all(),
          'error': error}) # XXX non members only

   if 'existing_user' in POST and POST['existing_user']!='None':
      u = User.objects.get(username=POST['existing_user'])
      u.groups.add(g)
      return render_to_response(
         'rat/project_manage.html',
         {'project': Project.objects.get(pk=project),
          'non_members': User.objects.all()}) # XXX non members only

   if 'new_project' in POST and POST['new_project']:
      error = None
      try:
         Project(name=POST['new_project']).save()
      except Exception, msg:
         error = msg
      return render_to_response(
         'rat/project_manage.html',
         {'project_list': Project.objects.all(),
          'error': error})
         
   for k, v in request.POST.items():
      if k.startswith('delete_'):
         project = request.POST['project']
         g = Project.objects.get(pk=project)
         u = User.objects.get(username=v)
         u.groups.remove(g) # XXX unsafe if user has requirements
   return render_to_response(
      'rat/project_manage.html',
      {'project': Project.objects.get(pk=project),
       'non_members': User.objects.filter()}) # XXX non members only

   
